﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Sx.Utils;
using Sx.Web.Admin.Models;
using Sx.Web.Framework;

namespace Sx.Web.Admin.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        
        public IActionResult Index()
        {
            return View();
        }
        public object Themes()
        {
            return AdminThemes.THEMEDIC.Select(kv => new { label = kv.Value, value = kv.Key }).ToList();
        } 

        public async Task<IActionResult> Contact()
        {
            ViewData["Message"] = "Your contact page.";
            await AuthHelper.SignInAsync("tangruixin", new { UserName = "tangruixin", NikeName = "dddddddddddd" });
            return View();
        }
        [AllowAnonymous]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
        public async Task<ActionResult> Logout(string returnurl)
        {
            await AuthHelper.SingOutAsync();
            return Redirect(returnurl ?? "~/");
        }
        [Route("Login")]
        [AllowAnonymous]
        [HttpGet]
        public IActionResult Login()
        { 
            return View();
        }

        [Route("Login")]
        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> LoginAjaxAsync()
        {
            string username = Request.Form["username"];
            string password = Request.Form["password"];

            UserService userService = new UserService();
            dynamic user = userService.Single("user_id,nickname,username,userpwd,salt", new   { username = username });
            if (user != null && user.username == username && user.userpwd == CryptoHelper.MD5( password+user.salt))
            {
                await AuthHelper.SignInAsync(user.user_id.ToString(), new { UserName = user.username, NikeName = user.nickname });
                return Json(new { status = 200, message = "登录成功！" });
            }
            else
            {
                return Json(new { status = 300, message = "账号或者密码错误！" });
            }
        }
    }
}
